package com.ruoyi.qywx.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.OkHttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.qywx.getway.request.TxRequest;
import com.ruoyi.qywx.service.inters.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : hcl
 * @Date : 2023/8/7
 */
@Service("qywxTokenService")
@Slf4j
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisCache redisCache;
    private final String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    @Override
    public String getToken(String corpId, String corpSecret) {
        String key = tokenKey(corpId, corpSecret);
        String accessToken = redisCache.getCacheObject(key);
        if (accessToken == null) {
            String url = tokenUrl + "?corpid=" + corpId + "&corpsecret=" + corpSecret;
            try {
                String str = OkHttpUtils.getInstance().getData(url, null);
                JSONObject resJson = JSONUtil.parseObj(str);
                if (resJson.getInt(TxRequest.ERR_CODE) == 0) {
                    accessToken = resJson.getStr(TxRequest.ACCESS_TOKEN);
                    redisCache.setCacheObject(key, accessToken, 7200, TimeUnit.SECONDS);
                    return accessToken;
                }
                log.error("获取token失败:corpId:{},corpSecret:{}", corpId, corpSecret);
            } catch (Exception e) {
                log.error("获取token失败:corpId:{},corpSecret:{}", corpId, corpSecret);
            }
        }
        return accessToken;
    }

    /**
     * 清理过期token
     */
    @Override
    public void clearPastToken(String corpId, String corpSecret) {
        redisCache.deleteObject(tokenKey(corpId, corpSecret));
    }

    private String tokenKey(String corpId, String corpSecret) {
        return Md5Utils.hash(corpId + "-" + corpSecret);
    }
}
